import Vue from 'vue'
import VueRouter from 'vue-router'
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Home = () => import('@/views/home')
const Article = () => import('@/views/article')
const Publish = () => import('@/views/publish')
import { getItem } from '@/utils/auth.js'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    redirect: '/home',
    component: Layout,
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/article',
        component: Article
      },
      {
        path: '/publish',
        component: Publish
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

/*
如果有token
 如果要去的页面是登录页
      跳转打首页
      如果要去的页面不是登录页
      正常进入
  如果没有token 
      只能去登录页
      如果要去的页面不是登录页
      跳转至登录页
 */
// 前置首位
router.beforeEach((to, form, next) => {
  Nprogress.start()
  if (getItem()) {
    if (to.path === '/login') {
      next('/home')
    } else {
      next()
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
  Nprogress.done()
})
// 后置守卫
router.afterEach((to, form) => {
  Nprogress.done()
  // console.log('afterEach:', to, form)
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
export default router
